using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//存储管理所有事件，提供订阅，取消订阅，触发事件的方法
public class EventManager : MonoBehaviour
{
    public delegate void EventHandler(object args);
    //管理所有委托
    Dictionary<int, EventHandler> m_events = new Dictionary<int, EventHandler>();

    public void Subscribe(int id, EventHandler handler)
    {
        if (!m_events.ContainsKey(id))
        {
            m_events.Add(id, null);
        }
        m_events[id] += handler;
    }

    public void UnSubscribe(int id, EventHandler handler)
    {
        if (m_events.ContainsKey(id))
        {
            if(m_events[id] != null)
            {
                m_events[id] -= handler;
            }
            else
            {
                m_events.Remove(id);
            }
        }
    }

    public void Fire(int id, object args = null)
    {
        if(m_events.TryGetValue(id, out EventHandler handler))
        {
            handler(args);
        }
    }
}
